﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.QPZS.EPC.API.Domain;
using Wicture.QPZS.EPC.API.Domain.Entities;

namespace Wicture.QPZS.EPC.API.InvokeContextBuilders
{
    public class RequestThrottedBuilder : IThrottedContextBuilder
    {
        public const string VinParameter = "vin";
        public const string BrandCodeParameter = "brandCode";
        public decimal Order => 1;

        public void Build(ThrottlingContext context, object sender, ApiInvokedArgs e)
        {
            var request = e.Context.HttpContext.Request;
            context.QueryString = request.QueryString.Value;
            var vinParameter = context.ServiceDefinition.VinParameter;
            if (string.IsNullOrEmpty(vinParameter))
            {
                vinParameter = VinParameter;
            }
            var brandCodeParameter = context.ServiceDefinition.BrandCodeParameter;
            if (string.IsNullOrEmpty(brandCodeParameter))
            {
                brandCodeParameter = BrandCodeParameter;
            }
            if (request.Method.Equals("get", StringComparison.CurrentCultureIgnoreCase))
            {
                var vin = request.Query.FirstOrDefault(q => q.Key.EqualsIgnoreCase(vinParameter)).Value;
                context.WithVin = !string.IsNullOrEmpty(vin);
                context.BrandCode = request.Query.FirstOrDefault(q => q.Key.EqualsIgnoreCase(brandCodeParameter)).Value;
            }
            else if (request.Method.Equals("post", StringComparison.CurrentCultureIgnoreCase))
            {
                var length = request.Body.Length;
                var bs = new byte[length];
                var body = request.Body.Read(bs, 0, (int)length);
                var json = JsonConvert.DeserializeObject<JToken>(Encoding.Default.GetString(bs));
                context.WithVin = json.Contains(vinParameter);
                context.BrandCode = json.Contains(brandCodeParameter) ? json.Value<string>(brandCodeParameter) : string.Empty;

            }
        }
    }
}
